package it.rossignoli.enrico.app.Tesi;

import it.rossignoli.enrico.app.Tesi.GestureActivity.ResponseReceiverGesture;
import it.rossignoli.enrico.app.Tesi.ListT.ResponseReceiverTraining;
import it.rossignoli.enrico.app.Tesi.MappingActivity.ResponseReceiverMapping;
import it.rossignoli.enrico.app.Tesi.RFIDActivity.ResponseReceiverRFID;
import it.rossignoli.enrico.app.Tesi.TesiActivity.ResponseReceiver;
import it.rossignoli.enrico.app.Tesi.sparql.SSAP_sparql_response;

import java.util.ArrayList;
import java.util.UUID;
import java.util.Vector;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;

public class SibIntentService extends IntentService {

	public enum typeIntent {
		CONNECT, RFID_CONTROL, RFID_CONNECTTO, GESTURE, MAPPING, DISCONNECT, LEAVE, REFRESH, INSERT
	}

	private typeIntent serviceTypeIntent;

	String IPTypeString;
	String NewIPTypeString;

	public static final boolean DEMO = true;
	public static final boolean DEBUG = false;

	/*
	 * Costanti per parametri delle shared preferences
	 */
	public final static String PARAM_IN_TYPE = "intent_TYPE";
	public final static String PARAM_IN_IP = "in_IP";
	public final static String PARAM_IN_SSNM = "in_SSNM";
	public final static String PARAM_IN_PORT = "in_PORT";
	public final static String PARAM_IN_NODEID = "in_NODEID";

	public final static String PARAM_IN_RFIDID = "in_RFIDID";

	public final static String PARAM_IN_EVENTFROMGESTURE = "in_EVENTFROMGESTURE";

	public final static String PARAM_OUT_MSG = "outmsg";
	public final static String PARAM_OUT_RESULT = "result";
	public final static String PARAM_OUT_DEVICENAME = "deviceName";
	public final static String PARAM_OUT_NODEVICE = "noDevice";

	private final static String URI = "URI";
	private final static String LITERAL = "literal";
	private final static String LOG_TAG = "SibIntentService";

	public static final String ACTION_LEAVEFROMSIB = "LEAVE";

	private ArrayList<String> deviceEvent;
	private ArrayList<String> gesture;

	/*
	 * --------------------------------------------------------------------------
	 * -----interaction primitive number attenzione! l'inserimento prevede un
	 * controllo non completo, controlla solo se esiste gi l'id dello
	 * smartobject come shared preferences, se tra un'esecuzione e l'altra
	 * cambia il numero di interactionprimitive non le inserisce e va in
	 * confusione (si potrebbe fermare). prevedere qualcosa
	 */
	private final static int INTERACTIONPRIMITIVE_NUMBER = 4;

	private it.rossignoli.enrico.app.Tesi.sparql.KPICore kp = null;
	private it.rossignoli.enrico.app.Tesi.sparql.SSAP_XMLTools xmlTools = null;
	private String xml = "";
	private boolean ack = false;
	// private SecureRandom random=new SecureRandom();

	/*
	 * --------------name spaces
	 */
	private String ns_arces = "";
	private String ns_core = "";
	private String ns_semint = "";
	private String ns_sc = "";
	private String ns_sc_add = "";
	/*
	 * ----------------------------------class
	 */
	private String SmartObject = "";
	private String MediaPlayer = "";
	private String MediaPlayerEvent = "";
	private String Resolution = "";
	private String Event = "";
	private String Identification = "";
	private String InteractionPrimitive = "";
	private String InteractionPrimitiveType = "";
	private String IDType = "";

	/*
	 * --------------------------properties
	 */

	private String connectedTo = "";
	private String hasIdentification = "";
	private String hasFriendlyName = "";
	private String launchesEvent = "";
	private String ofIDType = "";
	private String idValue = "";
	private String hasInteractionPrimitive = "";
	private String hasInteractionPrimitiveType = "";
	private String hasResolution = "";
	private String dataValue = "";
	private String canBeTransformedTo = "";
	private String hasEventType = "";
	private String supportEventType = "";

	public SibIntentService() {
		super(LOG_TAG);
		if (SibIntentService.DEBUG)
			Log.i(LOG_TAG, "Service Constructor.....................");
	}

	@Override
	public void onCreate() {
		super.onCreate();
		if (SibIntentService.DEBUG)
			Log.i(LOG_TAG, "Service Created........................");

		/*
		 * --------------------------------------------Init----------------------
		 * ------------------------
		 */

		ns_arces = getResources().getString(R.string.ns_arces);
		ns_core = getResources().getString(R.string.ns_core);
		ns_semint = getResources().getString(R.string.ns_semint);
		ns_sc = getResources().getString(R.string.ns_sc);
		ns_sc_add = getResources().getString(R.string.ns_sc_add);

		SmartObject = ns_core + getResources().getString(R.string.SmartObject);
		MediaPlayer = ns_core + getResources().getString(R.string.MediaPlayer);
		MediaPlayerEvent = ns_core + getResources().getString(R.string.MediaPlayerEvent);
		Resolution = ns_core + getResources().getString(R.string.Resolution);
		Event = ns_core + getResources().getString(R.string.Event);
		Identification = ns_core + getResources().getString(R.string.Identification);
		InteractionPrimitive = ns_semint + getResources().getString(R.string.InteractionPrimitive);
		InteractionPrimitiveType = ns_semint + getResources().getString(R.string.InteractionPrimitiveType);
		IDType = ns_semint + getResources().getString(R.string.IDType);

		/*
		 * ---------------------------------------Property------------------------
		 * ------------------
		 */

		connectedTo = ns_sc + "connectedTo";
		hasIdentification = ns_core + "hasIdentification";
		hasFriendlyName = ns_core + "hasFriendlyName";
		launchesEvent = ns_core + "launchesEvent";
		ofIDType = ns_semint + "ofIDType";
		idValue = ns_semint + "idValue";
		hasInteractionPrimitive = ns_semint + "hasInteractionPrimitive";
		hasInteractionPrimitiveType = ns_semint + "hasInteractionPrimitiveType";
		hasResolution = ns_semint + "hasResolution";
		dataValue = ns_semint + "dataValue";
		canBeTransformedTo = ns_semint + "canBeTransformedTo";
		hasEventType = ns_sc_add + "hasEventType";
		supportEventType = ns_sc_add + "supportEventType";

		if (SibIntentService.DEBUG)
			Log.i(LOG_TAG, "End Service Created.....................");

	}

	@Override
	public IBinder onBind(Intent arg0) {
		// Ritorniamo null in quanto non si vuole permettere
		// l'accesso al servizio da una applicazione diversa
		return null;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		if (SibIntentService.DEBUG)
			Log.i(LOG_TAG, "Service Destroyed");
	}

	@Override
	protected void onHandleIntent(Intent intent) {

		serviceTypeIntent = (typeIntent) intent.getSerializableExtra(PARAM_IN_TYPE);
		switch (serviceTypeIntent) {
		case CONNECT:
			response(intent, connect(intent));
			break;

		case REFRESH:
			response(intent, refesh(intent));
			break;

		case INSERT:
			response(intent, insert(intent));
			break;

		case RFID_CONTROL:
			response(intent, controlID(intent));
			break;

		case RFID_CONNECTTO:
			response(intent, connectTo(intent));
			break;

		case MAPPING:
			response(intent, mapping(intent));
			break;

		case GESTURE:
			response(intent, newGesture(intent));
			break;

		case DISCONNECT:
			response(intent, disconnect(intent));
			break;

		case LEAVE:
			response(intent, leave(intent));
			break;

		default:
			break;
		}

	}

	private boolean insert(Intent intent)

	{
		// TODO Auto-generated method stub
		boolean ret = false;
		// TODO Auto-generated method stub
		createKPICore();

		// inserisco la nuova interaction primitve type
		this.xml = this.kp.insert(ns_sc + intent.getStringExtra("NewIPType").toString(), "rdf:type", InteractionPrimitiveType, URI, URI);
		if (SibIntentService.DEBUG)
			Log.i(LOG_TAG, "Sib insert: " + this.xml + "\n");
		this.ack = this.xmlTools.isInsertConfirmed(this.xml);
		if (SibIntentService.DEBUG)
			Log.i(LOG_TAG, "Insert confirmed:" + (this.ack ? "YES" : "NO") + "\n");
		if (!this.ack) {
			if (SibIntentService.DEBUG)
				Log.i(LOG_TAG, "Can not INSERT the SIB: " + this.kp.getErrMess());
		}

		return ret;
	}

	private boolean refesh(Intent intent) {

		boolean ret = false;
		// TODO Auto-generated method stub
		createKPICore();

		// Prelevo le InteractionPrimitiveType che sono presenti in sib
		this.xml = this.kp.queryRDF(null, "rdf:type", InteractionPrimitiveType, URI, URI);
		this.ack = this.xmlTools.isQueryConfirmed(this.xml);
		if (SibIntentService.DEBUG)
			Log.i(LOG_TAG, "QUERY confirmed:" + (this.ack ? "YES" : "NO"));
		if (!this.ack) {
			if (SibIntentService.DEBUG)
				Log.i(LOG_TAG, "Can not QUERY connectedTo: " + this.kp.getErrMess());
		}
		ret = this.ack;

		StringBuilder sb = new StringBuilder();
		sb.append("");

		String temp;
		Vector<Vector<String>> IPType = this.xmlTools.getQueryTriple(this.xml);

		for (int i = 0; i < IPType.size(); i++) {
			temp = IPType.get(i).get(0).toString();

			sb.append(temp.substring(temp.indexOf("#") + 1)).append(",");
		}

		// creo la stringa che passer al sistema per creare la lista delle
		// interaction primitive type presenti in sib
		IPTypeString = sb.toString();

		return ret;
	}

	// interfaccia per la sib
	private void createKPICore() {
		if (this.kp == null) {

			/*
			 * parte senza l'utilizzo delle sharedpreferences
			 */
			// String ip=intent.getStringExtra(PARAM_IN_IP);
			// String ssnm=intent.getStringExtra(PARAM_IN_SSNM);
			// String port=intent.getStringExtra(PARAM_IN_PORT);
			// String nodeID=intent.getStringExtra(PARAM_IN_NODEID);

			/*
			 * parte con le sharedpreferences
			 */
			SharedPreferences pref = getSharedPreferences("PREFERENCES_SIB", Context.MODE_PRIVATE);
			String ip = pref.getString("TEXT_SIBIP", null);
			String ssnm = pref.getString("TEXT_SIBNAME", null);
			String port = pref.getString("TEXT_SIBPORT", null);
			String nodeID = pref.getString("TEXT_NODEID", null);
			/*
			 * fine parte sharedpreferences
			 */
			this.kp = new it.rossignoli.enrico.app.Tesi.sparql.KPICore(ip, Integer.parseInt(port), ssnm);
			// kp = new KPICore(ip,Integer.parseInt(port),ssnm);
			kp.setNodeID(nodeID);
			xmlTools = new it.rossignoli.enrico.app.Tesi.sparql.SSAP_XMLTools(nodeID, ssnm, null);
			if (SibIntentService.DEBUG)
				Log.i(LOG_TAG, "Recreate kpcore: " + this.xmlTools.toString() + " ip: " + ip + " name: " + ssnm + " port: " + port + " nodeid: " + nodeID + "\n");
			this.kp.enable_debug_message();
			this.kp.enable_error_message();
		}
	}

	private boolean controlID(Intent intent) {

		createKPICore();

		return controlIDSIB(intent);
	}

	private boolean newGesture(Intent intent) {
		boolean ret = false;

		createKPICore();

		ret = insertGestureSib(intent);

		// SystemClock.sleep(1000);

		return ret;
	}

	private boolean connect(Intent intent) {

		boolean ret = false;
		createKPICore();

		if (joinSib()) {
			if (insertBaseSib()) {
				ret = true;
			}
		}

		return ret;
	}

	private boolean mapping(Intent intent) {

		createKPICore();

		return insertMapping(intent);
	}

	private boolean joinSib() {
		this.xml = this.kp.join();
		if (SibIntentService.DEBUG)
			Log.i(LOG_TAG, "Sib message: " + this.xml + "\n");
		this.ack = this.xmlTools.isJoinConfirmed(this.xml);
		if (SibIntentService.DEBUG)
			Log.i(LOG_TAG, "Join confirmed:" + (this.ack ? "YES" : "NO") + "\n");
		if (!this.ack) {
			if (SibIntentService.DEBUG)
				Log.i(LOG_TAG, "Can not JOIN the SIB: " + this.kp.getErrMess());
		}
		return this.ack;
	}

	private boolean leaveSib() {
		this.xml = this.kp.leave();
		if (SibIntentService.DEBUG)
			Log.i(LOG_TAG, "Sib message: " + this.xml + "\n");
		this.ack = this.xmlTools.isLeaveConfirmed(this.xml);
		if (SibIntentService.DEBUG)
			Log.i(LOG_TAG, "Leave confirmed:" + (this.ack ? "YES" : "NO") + "\n");
		if (!this.ack) {
			if (SibIntentService.DEBUG)
				Log.i(LOG_TAG, "Can not LEAVE the SIB: " + this.kp.getErrMess());
		}
		return this.ack;
	}

	private boolean controlIDSIB(Intent intent) {

		boolean ret = false;

		String tagRFIDID = intent.getStringExtra(SibIntentService.PARAM_IN_RFIDID);
		this.xml = this.kp.queryRDF(null, this.idValue, tagRFIDID, "uri", "uri");

		String s = "['seq', ['inv', '" + idValue + "' ], ['inv', '" + hasIdentification + "'] ]";

		// s="SELECT ?mp WHERE{{ ?id <"+this.idValue+"> '"+tagRFIDID+"'}.{ ?mp <"+this.hasIdentification+"> ?id}}";
		s = "SELECT ?mp,?tag WHERE{{ ?id <" + this.idValue + "> ?tag}{ ?mp <http://www.sofia-project.eu/ontologies/core/2010/01/19/sofia.owl#hasIdentification> ?id}}";
		this.xml = this.kp.querySPARQL(s);
		// this.xml=this.kp.queryWQL_VALUES(tagRFIDID, LITERAL, s);
		if (SibIntentService.DEBUG)
			Log.i(LOG_TAG, "Sib query CONTROL ID SIB: " + this.xml + "\n");
		this.ack = this.xmlTools.isQueryConfirmed(this.xml);
		if (SibIntentService.DEBUG)
			Log.i(LOG_TAG, "Query confirmed:" + (this.ack ? "YES" : "NO") + "\n");
		if (!this.ack) {
			if (SibIntentService.DEBUG)
				Log.i(LOG_TAG, "Can not Query the SIB: " + this.kp.getErrMess());
		}
		ret = this.ack;



		SSAP_sparql_response sparqlResp = new SSAP_sparql_response(this.xml);

		// Vector<Vector<String[]>> v=sparqlResp.getResults();
		// Vector<Vector<String>> v= this.xmlTools.getWQLResultNode(this.xml);

		if (sparqlResp.hasResults()) {
			String mediaPlayer = "";
			Vector<String[]> readedTag,mpName;
			for(int i=0;i<sparqlResp.size();i++){
				readedTag=sparqlResp.getResultsForVar("tag");
				mpName=sparqlResp.getResultsForVar("mp");
				// recupero il valore del tag e lo confronto con quello che ho
				// letto dal sensore
				if (SSAP_sparql_response.getCellValue(readedTag.get(i)).compareTo(tagRFIDID.toString()) == 0) {
					mediaPlayer = SSAP_sparql_response.getCellValue(mpName.get(i));
					break;
				}
			}
			



			this.xml = this.kp.queryRDF(mediaPlayer, hasFriendlyName, null, URI, LITERAL);

			if (SibIntentService.DEBUG)
				Log.i(LOG_TAG, "Sib query device friendly name: " + this.xml + "\n");
			this.ack = this.xmlTools.isQueryConfirmed(this.xml);

			if (SibIntentService.DEBUG)
				Log.i(LOG_TAG, "query device friendly name confirmed:" + (this.ack ? "YES" : "NO") + "\n");
			if (!this.ack) {
				if (SibIntentService.DEBUG)
					Log.i(LOG_TAG, "Can not query device friendly name the SIB: " + this.kp.getErrMess());
			}
			if (SibIntentService.DEBUG)
				Log.i(LOG_TAG, this.xmlTools.getQueryTriple(this.xml).get(0).toString());

			String name = "";
			Vector<Vector<String>> VettoreName = this.xmlTools.getQueryTriple(this.xml);
			if (VettoreName.isEmpty()) {
				// vettore vuoto associo nome default
				name = "No_Name";
			} else {
				name = this.xmlTools.getQueryTriple(this.xml).get(0).get(2);
			}
			//
			//
			// if(SibIntentService.DEBUG)
			// Log.i(LOG_TAG,"--------------------------- DEVICE_NAME : "+name);
			//
			intent.putExtra("RFIDID_SIB", true);
			intent.putExtra("DEVICE_NAME", name);
			//
			// ret=this.ack;
		} else {
			intent.putExtra("RFIDID_SIB", false);
		}

		return ret;
	}

	private boolean connectTo(Intent intent) {
		boolean ret = false;
		createKPICore();

		String tagRFIDID = intent.getStringExtra(SibIntentService.PARAM_IN_RFIDID);
		String device = "";
		/*
		 * copiare la sintassi dalla macchina a stati python mi deve restituire
		 * l'uri del mediaplayer al quale mi voglio collegare
		 */

		String query = "SELECT ?mp,?tag WHERE{{ ?id <" + this.idValue + "> ?tag}{ ?mp <http://www.sofia-project.eu/ontologies/core/2010/01/19/sofia.owl#hasIdentification> ?id}}";
		this.xml = this.kp.querySPARQL(query);
		// this.xml=this.kp.queryWQL_VALUES(tagRFIDID, LITERAL, s);
		if (SibIntentService.DEBUG)
			Log.i(LOG_TAG, "Sib query CONTROL ID SIB: " + this.xml + "\n");
		this.ack = this.xmlTools.isQueryConfirmed(this.xml);
		if (SibIntentService.DEBUG)
			Log.i(LOG_TAG, "Query confirmed:" + (this.ack ? "YES" : "NO") + "\n");
		if (!this.ack) {
			if (SibIntentService.DEBUG)
				Log.i(LOG_TAG, "Can not Query the SIB: " + this.kp.getErrMess());
		}
		ret = this.ack;


		SSAP_sparql_response sparqlResp = new SSAP_sparql_response(this.xml);

		// Vector<Vector<String[]>> v=sparqlResp.getResults();
		// Vector<Vector<String>> v= this.xmlTools.getWQLResultNode(this.xml);

		if (sparqlResp.hasResults()) {
			Vector<String[]> readedTag,mpName;
			for(int i=0;i<sparqlResp.size();i++){
				readedTag=sparqlResp.getResultsForVar("tag");
				mpName=sparqlResp.getResultsForVar("mp");
				// recupero il valore del tag e lo confronto con quello che ho
				// letto dal sensore
				if (SSAP_sparql_response.getCellValue(readedTag.get(i)).compareTo(tagRFIDID.toString()) == 0) {
					device = SSAP_sparql_response.getCellValue(mpName.get(i));
					break;
				}
			}

			/*
			 * una volta recuperato il valore del mediaplayer posso creare la
			 * connectTo, creo una rdf con smartobject_xxx connectTo
			 * mediaplayer_yyy quindi devo avere anche il valore di
			 * smartobject_xxx
			 */
			this.xml = this.kp.queryRDF(device, hasFriendlyName, null, URI, LITERAL);
			if (SibIntentService.DEBUG)
				Log.i(LOG_TAG, "Sib query device friendly name: " + this.xml + "\n");
			this.ack = this.xmlTools.isQueryConfirmed(this.xml);
			if (SibIntentService.DEBUG)
				Log.i(LOG_TAG, "query device friendly name confirmed:" + (this.ack ? "YES" : "NO") + "\n");
			if (!this.ack) {
				if (SibIntentService.DEBUG)
					Log.i(LOG_TAG, "Can not query device friendly name the SIB: " + this.kp.getErrMess());
			}
			if (SibIntentService.DEBUG)
				Log.i(LOG_TAG, this.xmlTools.getQueryTriple(this.xml).get(0).toString());
			String name = "";
			Vector<Vector<String>> VettoreName = this.xmlTools.getQueryTriple(this.xml);
			if (VettoreName.isEmpty()) {
				// vettore vuoto associo nome default
				name = "No_Name";
			} else {
				name = this.xmlTools.getQueryTriple(this.xml).get(0).get(2);
			}

			if (ret) {
				ret = this.ack;
			}

			SharedPreferences pref = getSharedPreferences("PREFERENCES_SMARTOBJECT", Context.MODE_PRIVATE);
			String SmartObject_id = pref.getString("SMARTOBJECT_ID", null);
			SharedPreferences.Editor editor = pref.edit();
			editor.putString("DEVICE", device);
			editor.putString("DEVICE_NAME", name);

			editor.commit();

			this.xml = this.kp.insert(SmartObject_id, connectedTo, device, URI, URI);
			if (SibIntentService.DEBUG)
				Log.i(LOG_TAG, "Sib insert: " + this.xml + "\n");
			this.ack = this.xmlTools.isInsertConfirmed(this.xml);
			if (SibIntentService.DEBUG)
				Log.i(LOG_TAG, "Insert confirmed:" + (this.ack ? "YES" : "NO") + "\n");
			if (!this.ack) {
				if (SibIntentService.DEBUG)
					Log.i(LOG_TAG, "Can not INSERT the SIB: " + this.kp.getErrMess());
			}

			if (ret) {
				ret = this.ack;
			}

			if (SibIntentService.DEBUG)
				Log.i(LOG_TAG, "Prima della query rdf per i mediaplayerevent");

			this.xml = this.kp.queryRDF(device, supportEventType, null, URI, URI);
			if (SibIntentService.DEBUG)
				Log.i(LOG_TAG, "Sib query Device event: " + this.xml + "\n");
			this.ack = this.xmlTools.isQueryConfirmed(this.xml);
			if (SibIntentService.DEBUG)
				Log.i(LOG_TAG, "Query confirmed:" + (this.ack ? "YES" : "NO") + "\n");
			if (!this.ack) {
				if (SibIntentService.DEBUG)
					Log.i(LOG_TAG, "Can not Query the SIB: " + this.kp.getErrMess());
			}
			if (ret) {
				ret = this.ack;
			}

			deviceEvent = new ArrayList<String>();
			for (Vector<String> v : this.xmlTools.getQueryTriple(this.xml)) {
				if (SibIntentService.DEBUG)
					Log.i(LOG_TAG, v.get(0));
				if (SibIntentService.DEBUG)
					Log.i(LOG_TAG, v.get(1));
				if (SibIntentService.DEBUG)
					Log.i(LOG_TAG, v.get(2));
				deviceEvent.add(v.get(2));
			}

			/*
			 * gestione preferenze passate inserite nella sib!
			 */

			StringBuilder sb = new StringBuilder();
			sb.append("");
			for (String s : deviceEvent) {
				this.xml = this.kp.queryRDF(null, canBeTransformedTo, s, URI, URI);
				if (SibIntentService.DEBUG)
					Log.i(LOG_TAG, "--------------------------------------Sib query DEVICE PREVIOUS event: " + this.xml + "\n");
				this.ack = this.xmlTools.isQueryConfirmed(this.xml);
				if (SibIntentService.DEBUG)
					Log.i(LOG_TAG, "Query confirmed:" + (this.ack ? "YES" : "NO") + "\n");
				if (!this.ack) {
					if (SibIntentService.DEBUG)
						Log.i(LOG_TAG, "Can not Query the SIB: " + this.kp.getErrMess());
				}

				if (ret) {
					ret = this.ack;
				}

				if (!this.xmlTools.getQueryTriple(this.xml).isEmpty()) {
					for (Vector<String> singleResp : this.xmlTools.getQueryTriple(this.xml)) {
						String interactionPrimitive = singleResp.get(0);
						if (SibIntentService.DEBUG)
							Log.i(LOG_TAG, "----------------- : " + interactionPrimitive);
						this.xml = this.kp.queryRDF(null, hasInteractionPrimitive, interactionPrimitive, URI, URI);
						if (SibIntentService.DEBUG)
							Log.i(LOG_TAG, "Sib query Device event: " + this.xml + "\n");
						this.ack = this.xmlTools.isQueryConfirmed(this.xml);
						if (SibIntentService.DEBUG)
							Log.i(LOG_TAG, "Query confirmed:" + (this.ack ? "YES" : "NO") + "\n");
						if (!this.ack) {
							if (SibIntentService.DEBUG)
								Log.i(LOG_TAG, "Can not Query the SIB: " + this.kp.getErrMess());
						}

						if (ret) {
							ret = this.ack;
						}

						String smartObj = this.xmlTools.getQueryTriple(this.xml).get(0).get(0);
						if (SibIntentService.DEBUG)
							Log.i(LOG_TAG, "----------------- : " + smartObj);
						if (smartObj.equals(SmartObject_id)) {
							this.xml = this.kp.queryRDF(interactionPrimitive, hasInteractionPrimitiveType, null, URI, URI);
							if (SibIntentService.DEBUG)
								Log.i(LOG_TAG, "Sib query Device event: " + this.xml + "\n");
							this.ack = this.xmlTools.isQueryConfirmed(this.xml);
							if (SibIntentService.DEBUG)
								Log.i(LOG_TAG, "Query confirmed:" + (this.ack ? "YES" : "NO") + "\n");
							if (!this.ack) {
								if (SibIntentService.DEBUG)
									Log.i(LOG_TAG, "Can not Query the SIB: " + this.kp.getErrMess());
							}
							if (ret) {
								ret = this.ack;
							}

							String ges = this.xmlTools.getQueryTriple(this.xml).get(0).get(2);
							if (SibIntentService.DEBUG)
								Log.i(LOG_TAG, "----------------- : " + ges);
							sb.append(ges).append("=").append(s).append(";");

							/*
							 * rimuovo dalla sib la vecchia canBeTransformedTo
							 */
							this.xml = this.kp.remove(interactionPrimitive, canBeTransformedTo, s, URI, URI);
							if (SibIntentService.DEBUG)
								Log.i(LOG_TAG, "Sib REMOVE canBeTransformedTo: " + this.xml + "\n");
							this.ack = this.xmlTools.isRemoveConfirmed(this.xml);
							if (SibIntentService.DEBUG)
								Log.i(LOG_TAG, "REMOVE confirmed:" + (this.ack ? "YES" : "NO") + "\n");
							if (!this.ack) {
								if (SibIntentService.DEBUG)
									Log.i(LOG_TAG, "Can not REMOVE canBeTransformedTo: " + this.kp.getErrMess());
							}
							if (ret) {
								ret = this.ack;
							}

						}
					}
				}
			}
			// editor.putString("COMPLETEMAPPING", sb.toString());
			// editor.commit();
			if (!sb.equals("")) {
				intent.putExtra("PREVIOUSMAPPING", sb.toString());
				if (SibIntentService.DEBUG)
					Log.i(LOG_TAG, "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx PREVIOUSMAPPING :" + sb.toString());
			}

			if (SibIntentService.DEBUG)
				Log.i(LOG_TAG, "Prima della query rdf per i gesti");

			gesture = new ArrayList<String>();
			String smipt = pref.getString("SMARTOBJECT_INTERACTIONPRIMITIVE_TYPE", null);
			String temp[] = new String[INTERACTIONPRIMITIVE_NUMBER];
			temp = smipt.split(",");
			for (int i = 0; i < temp.length; i++) {
				gesture.add(temp[i]);
			}

		}

		if (ret == true) {
			ret = this.ack;
		}

		return ret;

	}

	private boolean insertBaseSib() {

		boolean ret = false;

		/*
		 * --------------------------------------------instance------------------
		 * ----------------------------
		 */

		String SmartObject_01 = null;

		String SmartObjectInteractionPrimitive[] = new String[INTERACTIONPRIMITIVE_NUMBER];

		/*
		 * ------------------------------------------------insert gesture
		 * (interaction primitive
		 * type)------------------------------------------------------- sviluppo
		 * futuro: inserimento dei gesti tramite training gesti e salvataggio in
		 * un file o sharedprefereces, qui vengono recuperati e inseriti nella
		 * sib. Da modificare anche la costante INTERACTIONPRIMITIVE_NUMBER che
		 * per adesso appunto costante, magari con un contatore di
		 * interactionprimitivetype (si potrebbe modificare anche String[] in
		 * arrayList)
		 */

		//
		String MoveDown = ns_sc + "MoveDown";
		String MoveUp = ns_sc + "MoveUp";
		String MoveRight = ns_sc + "MoveRight";
		String MoveLeft = ns_sc + "MoveLeft";

		gesture = new ArrayList<String>();
		gesture.add(MoveUp);
		gesture.add(MoveDown);
		gesture.add(MoveRight);
		gesture.add(MoveLeft);

		// Riempio le preferences per lo smartobject

		SharedPreferences pref = getSharedPreferences("PREFERENCES_SMARTOBJECT", Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = pref.edit();
		if (!pref.contains("SMARTOBJECT_ID")) {

			// SmartObject_01= SmartObject+"_"+random.nextInt(RANDOM_LIMIT);
			SmartObject_01 = SmartObject + "_" + UUID.randomUUID().toString();
			editor.putString("SMARTOBJECT_ID", SmartObject_01);
		}
		if ((!pref.contains("SMARTOBJECT_INTERACTIONPRIMITIVE")) || ((pref.getInt("SMARTOBJECT_INTERACTIONPRIMITIVE_NUMBER", 0)) != INTERACTIONPRIMITIVE_NUMBER)) {
			editor.putInt("SMARTOBJECT_INTERACTIONPRIMITIVE_NUMBER", SmartObjectInteractionPrimitive.length);
			if (SibIntentService.DEBUG)
				Log.i(LOG_TAG, "SMARTOBJECT_INTERACTIONPRIMITIVE_NUMBER " + SmartObjectInteractionPrimitive.length);
			StringBuilder sb = new StringBuilder();
			for (int i = 0; i < SmartObjectInteractionPrimitive.length; i++) {
				// SmartObjectInteractionPrimitive[i]=InteractionPrimitive+"_"+random.nextInt(RANDOM_LIMIT);
				SmartObjectInteractionPrimitive[i] = InteractionPrimitive + "_" + UUID.randomUUID().toString();
				sb.append(SmartObjectInteractionPrimitive[i]).append(",");
			}
			editor.putString("SMARTOBJECT_INTERACTIONPRIMITIVE", sb.toString());
		}

		if ((!pref.contains("SMARTOBJECT_INTERACTIONPRIMITIVE_TYPE")) || ((pref.getInt("SMARTOBJECT_INTERACTIONPRIMITIVE_NUMBER", 0)) != INTERACTIONPRIMITIVE_NUMBER)) {
			StringBuilder sb = new StringBuilder();
			for (String s : gesture) {
				sb.append(s).append(",");
			}
			editor.putString("SMARTOBJECT_INTERACTIONPRIMITIVE_TYPE", sb.toString());
		}
		editor.commit();

		// prelevo dalle preferences cio che mi serve da mettere in sib
		SmartObject_01 = pref.getString("SMARTOBJECT_ID", null);
		if (SibIntentService.DEBUG)
			Log.i(LOG_TAG, "SMARTOBJECT_INTERACTIONPRIMITIVE_NUMBER " + SmartObjectInteractionPrimitive.length);

		// stringa contenente tutte le interactionpritive da inserire nella sib
		// (Una per ogni interation pritive type presente in sib) separate da
		// virgole
		String smip = pref.getString("SMARTOBJECT_INTERACTIONPRIMITIVE", null);
		// vettore riempito con le intearction primtive
		SmartObjectInteractionPrimitive = smip.split(",");

		String smipt = pref.getString("SMARTOBJECT_INTERACTIONPRIMITIVE_TYPE", null);
		String temp[] = new String[INTERACTIONPRIMITIVE_NUMBER];
		temp = smipt.split(",");
		for (int i = 0; i < temp.length; i++) {
			gesture.add(temp[i]);
		}

		Vector<Vector<String>> instance = null;
		instance = new Vector<Vector<String>>();

		/*
		 * questa parte la inserisco tutte le volte, ma in realt cambia i valori
		 * solo alla prima esecuzione dell'app, o se cancello i dati relativi
		 * all'app.
		 */

		// Aggiunge l istanza dello smrtobject della classe smartobject
		instance.add(this.xmlTools.newTriple(SmartObject_01, "rdf:type", SmartObject, URI, URI));
		// aggiunge le istanze di interaction primitive alla sib
		for (int i = 0; i < SmartObjectInteractionPrimitive.length; i++) {
			instance.add(this.xmlTools.newTriple(SmartObjectInteractionPrimitive[i], "rdf:type", InteractionPrimitive, URI, URI));
		}

		this.xml = this.kp.insert(instance);
		this.ack = this.xmlTools.isInsertConfirmed(this.xml);
		if (SibIntentService.DEBUG)
			Log.i(LOG_TAG, "Insert instance confirmed:" + (this.ack ? "YES" : "NO"));
		if (!this.ack) {
			if (SibIntentService.DEBUG)
				Log.i(LOG_TAG, "Can not INSERT DATA instance into the SIB " + this.kp.getErrMess());
		}
		ret = this.ack;

		// collego le istanze di interaction primitive allo smartobject
		Vector<Vector<String>> attributes = null;
		attributes = new Vector<Vector<String>>();

		for (int i = 0; i < SmartObjectInteractionPrimitive.length; i++) {
			// attributes.add( this.xmlTools.newTriple(
			// SmartObjectInteractionPrimitive[i], dataValue , "false", URI,
			// LITERAL) );
			attributes.add(this.xmlTools.newTriple(SmartObject_01, hasInteractionPrimitive, SmartObjectInteractionPrimitive[i], URI, URI));
			attributes.add(this.xmlTools.newTriple(SmartObjectInteractionPrimitive[i], hasInteractionPrimitiveType, temp[i], URI, URI));
		}

		this.xml = this.kp.insert(attributes);
		this.ack = this.xmlTools.isInsertConfirmed(this.xml);
		if (SibIntentService.DEBUG)
			Log.i(LOG_TAG, "Insert attributes confirmed:" + (this.ack ? "YES" : "NO"));
		if (!this.ack) {
			if (SibIntentService.DEBUG)
				Log.i(LOG_TAG, "Can not INSERT DATA attributes into the SIB " + this.kp.getErrMess());
		}

		if (ret == true) {
			ret = this.ack;
		}

		return ret;

	}

	private boolean insertGestureSib(Intent intent) {
		boolean ret = false;
		boolean enable = true;
		String eventFromGesture = intent.getStringExtra(PARAM_IN_EVENTFROMGESTURE);

		if (!eventFromGesture.equals(MappingActivity.NULL_ELEMENT)) {
			SharedPreferences pref = getSharedPreferences("PREFERENCES_SMARTOBJECT", Context.MODE_PRIVATE);
			String SmartObject_id = pref.getString("SMARTOBJECT_ID", null);
			String device_id = pref.getString("DEVICE", null);

			// ritorna tutti i controllori(smartphone) che sono connessi al
			// controllato(mediaplayer)
			this.xml = this.kp.queryRDF(null, connectedTo, device_id, URI, URI);
			this.ack = this.xmlTools.isQueryConfirmed(this.xml);
			if (SibIntentService.DEBUG)
				Log.i(LOG_TAG, "QUERY confirmed:" + (this.ack ? "YES" : "NO"));
			if (!this.ack) {
				if (SibIntentService.DEBUG)
					Log.i(LOG_TAG, "Can not QUERY connectedTo: " + this.kp.getErrMess());
			}
			ret = this.ack;

			// uri smrtobject trovati
			if (!this.xmlTools.getQueryTriple(this.xml).isEmpty()) {
				enable = true;
				Vector<Vector<String>> vec = new Vector<Vector<String>>();
				for (Vector<String> v : this.xmlTools.getQueryTriple(this.xml)) {
					// vettore che rappresenta la query di richiesta se qualche
					// altro so ha eventi attivi di qualsiasi genere sul
					// controllato
					Vector<String> vv = new Vector<String>();
					vv.add(v.get(0)); // controllore (S.O.)
					vv.add(launchesEvent);
					vv.add(null); // oggetto (evento) di qualsiasi genere (null)
					vv.add(URI);
					vv.add(URI);
					vec.add(vv);
				}

				this.xml = this.kp.queryRDF(vec);
				this.ack = this.xmlTools.isQueryConfirmed(this.xml);
				if (SibIntentService.DEBUG)
					Log.i(LOG_TAG, "QUERY confirmed:" + (this.ack ? "YES" : "NO"));
				if (!this.ack) {
					if (SibIntentService.DEBUG)
						Log.i(LOG_TAG, "Can not QUERY connectedTo: " + this.kp.getErrMess());
				}

				// Se true nessun controllore sta eseguendo gesti sul
				// controllato
//				if (!this.xmlTools.getQueryTriple(this.xml).isEmpty())
//					enable = false;
			}

			if (enable) {
				// String Event_xx=Event+"_"+random.nextInt(RANDOM_LIMIT);
				String Event_xx = Event + "_" + UUID.randomUUID().toString();

				// effettuo la insert
				Vector<Vector<String>> triples = null;
				triples = new Vector<Vector<String>>();

				triples.add(this.xmlTools.newTriple(Event_xx, "rdf:type", Event, URI, URI));
				triples.add(this.xmlTools.newTriple(SmartObject_id, launchesEvent, Event_xx, URI, URI));
				triples.add(this.xmlTools.newTriple(Event_xx, hasEventType, eventFromGesture, URI, URI));

				this.xml = this.kp.insert(triples);
				this.ack = this.xmlTools.isInsertConfirmed(this.xml);
				if (SibIntentService.DEBUG)
					Log.i(LOG_TAG, "Insert confirmed:" + (this.ack ? "YES" : "NO"));
				if (!this.ack) {
					if (SibIntentService.DEBUG)
						Log.i(LOG_TAG, "Can not INSERT DATA into the SIB " + this.kp.getErrMess());
				}
				if (ret) {
					ret = this.ack;
				}
			}
		}
		intent.putExtra("GESTURE_CONFIRM", enable);
		return ret;
	}

	private boolean insertMapping(Intent intent) {

		boolean ret = false;
		SharedPreferences pref = getSharedPreferences("PREFERENCES_SMARTOBJECT", Context.MODE_PRIVATE);
		String sMapping = pref.getString("COMPLETEMAPPING", null);

		String[] singleMapping = new String[INTERACTIONPRIMITIVE_NUMBER];
		singleMapping = sMapping.split(";");

		for (int i = 0; i < INTERACTIONPRIMITIVE_NUMBER; i++) {
			String[] temp = new String[2];
			String intPrim = "";

			temp = singleMapping[i].split("=");
			if (!temp[1].equals(MappingActivity.NULL_ELEMENT)) {
				/*
				 * query che risale dal interactionprimitiveType
				 * all'interactionprimitive e da li crea la canBeTransformedTo
				 */
				this.xml = this.kp.queryRDF(null, hasInteractionPrimitiveType, temp[0], URI, URI);
				if (SibIntentService.DEBUG)
					Log.i(LOG_TAG, "Sib query interactionprimitive: " + this.xml + "\n");
				this.ack = this.xmlTools.isQueryConfirmed(this.xml);
				if (SibIntentService.DEBUG)
					Log.i(LOG_TAG, "Query confirmed:" + (this.ack ? "YES" : "NO") + "\n");
				if (!this.ack) {
					if (SibIntentService.DEBUG)
						Log.i(LOG_TAG, "Can not Query the SIB: " + this.kp.getErrMess());
				}
				ret = this.ack;

				intPrim = this.xmlTools.getQueryTriple(this.xml).get(0).get(0);

				if (SibIntentService.DEBUG)
					Log.i(LOG_TAG, this.xmlTools.getQueryTriple(this.xml).get(0).get(0));

				this.xml = this.kp.insert(intPrim, canBeTransformedTo, temp[1], URI, URI);
				if (SibIntentService.DEBUG)
					Log.i(LOG_TAG, "Sib insert canBeTransformedTo: " + this.xml + "\n");
				this.ack = this.xmlTools.isInsertConfirmed(this.xml);
				if (SibIntentService.DEBUG)
					Log.i(LOG_TAG, "Insert canBeTransformedTo confirmed:" + (this.ack ? "YES" : "NO") + "\n");
				if (!this.ack) {
					if (SibIntentService.DEBUG)
						Log.i(LOG_TAG, "Can not INSERT canBeTransformedTo the SIB: " + this.kp.getErrMess());
				}
				if (ret) {
					ret = this.ack;
				}
			}

		}

		return ret;
	}

	private boolean disconnect(Intent intent) {
		createKPICore();

		SharedPreferences pref = getSharedPreferences("PREFERENCES_SMARTOBJECT", Context.MODE_PRIVATE);
		String SmartObject_id = pref.getString("SMARTOBJECT_ID", null);
		String device = pref.getString("DEVICE", null);

		this.xml = this.kp.remove(SmartObject_id, connectedTo, device, URI, URI);
		if (SibIntentService.DEBUG)
			Log.i(LOG_TAG, "Sib REMOVE connectedTo: " + this.xml + "\n");
		this.ack = this.xmlTools.isRemoveConfirmed(this.xml);
		if (SibIntentService.DEBUG)
			Log.i(LOG_TAG, "Remove confirmed:" + (this.ack ? "YES" : "NO") + "\n");
		if (!this.ack) {
			if (SibIntentService.DEBUG)
				Log.i(LOG_TAG, "Can not Remove canBeTransformedTo: " + this.kp.getErrMess());
		}

		return this.ack;
	}

	private boolean leave(Intent intent) {

		boolean ret = false;
		createKPICore();

		SharedPreferences pref = getSharedPreferences("PREFERENCES_SMARTOBJECT", MODE_PRIVATE);
		String SO_id = pref.getString("SMARTOBJECT_ID", null);

		this.xml = this.kp.queryRDF(SO_id, connectedTo, null, URI, URI);
		this.ack = this.xmlTools.isQueryConfirmed(this.xml);
		if (SibIntentService.DEBUG)
			Log.i(LOG_TAG, "Query connectedTo confirmed:" + (this.ack ? "YES" : "NO"));
		if (!this.ack) {
			if (SibIntentService.DEBUG)
				Log.i(LOG_TAG, "Can not Query connectedTo : " + this.kp.getErrMess());
		}
		ret = this.ack;

		if (!this.xmlTools.getQueryTriple(this.xml).isEmpty()) {
			String device = this.xmlTools.getQueryTriple(this.xml).get(0).get(2);

			this.xml = this.kp.remove(SO_id, connectedTo, device, URI, URI);
			this.ack = this.xmlTools.isRemoveConfirmed(this.xml);
			if (SibIntentService.DEBUG)
				Log.i(LOG_TAG, "REMOVE connectedTo confirmed:" + (this.ack ? "YES" : "NO"));
			if (!this.ack) {
				if (SibIntentService.DEBUG)
					Log.i(LOG_TAG, "Can not REMOVE connectedTo : " + this.kp.getErrMess());
			}
			if (ret) {
				ret = this.ack;
			}
		}

		if (ret) {
			ret = leaveSib();
		}

		return ret;
	}

	private void response(Intent intent, boolean r) {
		serviceTypeIntent = (typeIntent) intent.getSerializableExtra(PARAM_IN_TYPE);
		switch (serviceTypeIntent) {
		case CONNECT:
			Intent broadcastIntent = new Intent();
			broadcastIntent.setAction(ResponseReceiver.ACTION_RESP);
			broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
			broadcastIntent.putExtra(PARAM_OUT_RESULT, r);
			sendBroadcast(broadcastIntent);
			break;

		case REFRESH:
			Intent broadcastIntent7 = new Intent();
			broadcastIntent7.setAction(ResponseReceiverTraining.ACTION_RESP_TRAIN);
			broadcastIntent7.addCategory(Intent.CATEGORY_DEFAULT);
			broadcastIntent7.putExtra(PARAM_OUT_RESULT, r);
			broadcastIntent7.putExtra("IPType", IPTypeString);
			sendBroadcast(broadcastIntent7);
			break;

		case INSERT:
			Intent broadcastIntent8 = new Intent();
			broadcastIntent8.setAction(ResponseReceiverTraining.ACTION_RESP_TRAIN_REFRESH);
			broadcastIntent8.addCategory(Intent.CATEGORY_DEFAULT);
			broadcastIntent8.putExtra(PARAM_OUT_RESULT, r);
			// broadcastIntent8.putExtra("NewIPTYPE", NewIPTypeString);
			sendBroadcast(broadcastIntent8);
			break;

		case RFID_CONTROL:
			Intent broadcastIntent2 = new Intent();
			broadcastIntent2.setAction(ResponseReceiverRFID.ACTION_RESP_RFID_CONTROL);
			broadcastIntent2.addCategory(Intent.CATEGORY_DEFAULT);
			broadcastIntent2.putExtra(PARAM_OUT_RESULT, r);
			if (intent.getBooleanExtra("RFIDID_SIB", false)) {
				broadcastIntent2.putExtra("DEVICE_NAME", intent.getStringExtra("DEVICE_NAME"));
			} else {
				broadcastIntent2.putExtra("DEVICE_NAME", PARAM_OUT_NODEVICE);
			}

			sendBroadcast(broadcastIntent2);
			break;

		case RFID_CONNECTTO:
			broadcastIntent2 = new Intent();
			broadcastIntent2.setAction(ResponseReceiverRFID.ACTION_RESP_RFID_CONNECTTO);
			broadcastIntent2.addCategory(Intent.CATEGORY_DEFAULT);
			broadcastIntent2.putExtra("DEVICE_EVENTLIST", deviceEvent);
			broadcastIntent2.putExtra("SMARTOBJECT_GESTURELIST", gesture);
			if (intent.hasExtra("PREVIOUSMAPPING"))
				broadcastIntent2.putExtra("PREVIOUSMAPPING", intent.getStringExtra("PREVIOUSMAPPING"));
			broadcastIntent2.putExtra(PARAM_OUT_RESULT, r);
			sendBroadcast(broadcastIntent2);
			break;

		case MAPPING:
			Intent broadcastIntent3 = new Intent();
			broadcastIntent3.setAction(ResponseReceiverMapping.ACTION_RESP_MAPPING);
			broadcastIntent3.addCategory(Intent.CATEGORY_DEFAULT);
			broadcastIntent3.putExtra(PARAM_OUT_RESULT, r);
			sendBroadcast(broadcastIntent3);
			break;

		case GESTURE:
			Intent broadcastIntent4 = new Intent();
			broadcastIntent4.setAction(ResponseReceiverGesture.ACTION_RESP_GESTURE);
			broadcastIntent4.addCategory(Intent.CATEGORY_DEFAULT);
			broadcastIntent4.putExtra(PARAM_OUT_RESULT, r);
			broadcastIntent4.putExtra("GESTURE_CONFIRM", intent.getBooleanExtra("GESTURE_CONFIRM", true));
			sendBroadcast(broadcastIntent4);
			break;

		case DISCONNECT:
			Intent broadcastIntent5 = new Intent();
			broadcastIntent5.setAction(ResponseReceiverGesture.ACTION_RESP_DISCONNECT);
			broadcastIntent5.addCategory(Intent.CATEGORY_DEFAULT);
			broadcastIntent5.putExtra(PARAM_OUT_RESULT, r);
			sendBroadcast(broadcastIntent5);
			break;

		/*
		 * ancora da implementare
		 */
		case LEAVE:
			Intent broadcastIntent6 = new Intent();
			broadcastIntent6.setAction(ACTION_LEAVEFROMSIB);
			broadcastIntent6.addCategory(Intent.CATEGORY_DEFAULT);
			broadcastIntent6.putExtra(PARAM_OUT_RESULT, r);
			sendBroadcast(broadcastIntent6);
			break;

		default:
			break;
		}
	}

}
